package com.jstyle.jclife.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;

import com.jstyle.jclife.R;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.SleepDataDaoManager;
import com.jstyle.jclife.daoManager.StepDetailDataDaoManager;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.SleepData;
import com.jstyle.jclife.model.StepDetailData;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CsvUtils {

    public static void createCsvFile(Context context) {
        File csvFile = null;
        BufferedWriter csvWtriter = null;
        csvFile = new File(ImageUtils.mapPath + "test.csv");
        File parent = csvFile.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        try {
            csvFile.createNewFile();
            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);
            String[] head = {"Date", "Heart Rate", "Calorie", "Distance", "Step","Sleep Quality"};
            List<String> headList = Arrays.asList(head);
            HashMap<Integer,String[]>dataHashMap=new HashMap<>();
            String startDate = "19.07.07 00:00:00";
            initData(dataHashMap,startDate);
            List<StepDetailData> stepDetailDataList = StepDetailDataDaoManager.queryData("19.07.07", "19.07.08");
            List<HeartData> heartDataList = HeartDataDaoManager.queryData("19.07.07", "19.07.08");
            for (HeartData heartData : heartDataList) {
                String date = heartData.getTime();
                int count = DateUtil.get1MIndex(date, startDate);
                int heartRate = heartData.getHeart();
                String[]data=dataHashMap.get(count);
                data[1]=String.valueOf(heartRate);
//                StringBuffer stringBuffer = new StringBuffer();
//                stringBuffer.append("\"").append(date).append("\",")
//                        .append("\"").append(heartRate).append("\",");
//                dataArrays[count] = stringBuffer.toString();
            }
            for (StepDetailData stepDetailData : stepDetailDataList) {
                String date = stepDetailData.getDate();
                int count = DateUtil.get1MIndex(date, startDate);
                String cal = stepDetailData.getCal();
                String distance = stepDetailData.getDistance();
                String detailSteps = stepDetailData.getMinterStep();
                String[] stepArray = detailSteps.split(" ");
                for (int i = 0; i < stepArray.length; i++) {
                    String[]data=dataHashMap.get(count+i);
                    data[2]=cal;
                    data[3]=distance;
                    data[4]=stepArray[i];
                }


            }


            List<SleepData> sleepDataList = SleepDataDaoManager.queryData("19.07.07", "19.07.08");
            for(SleepData sleepData:sleepDataList){
                String time=sleepData.getTime();
                String data=sleepData.getDateString();
                int startCount = DateUtil.get1MIndex(time, startDate);

                Log.i(TAG, "createSleepCsvFile: "+time+" "+data);
                for(int i=startCount;i<startCount+5;i++){
                    String[]dataArray=dataHashMap.get(i);
                    dataArray[5]=Integer.valueOf(data) == 0 ? "--" : Integer.valueOf(data)+"";
                }


            }
            writeRow(headList, csvWtriter);
            for (Map.Entry<Integer, String[]> entry : dataHashMap.entrySet()) {
                String[] values = entry.getValue();
                writeRowContent(values, csvWtriter);
            }
//            for (List<String> list : dataList) {
//                writeRow(list, csvWtriter);
//            }
           // List<String> contentList = Arrays.asList(dataArrays);
            //writeRowContent(contentList, csvWtriter);
            csvWtriter.flush();
            csvWtriter.close();
        } catch (
                IOException e) {
            e.printStackTrace();
        }
        shareByPhone(context,csvFile.getAbsolutePath());
    }
    public static void shareByPhone(Context context,String path){
        Uri imageUri=null;
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(context.getApplicationContext(),
                    context.getString(R.string.fileprovider), new File(path));
        } else {
            imageUri = Uri.fromFile(new File(path));
        }
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("*/*");
        context.startActivity(Intent.createChooser(shareIntent, "分享到"));
    }

    private static final String TAG = "CsvUtils";
    public static void createSleepCsvFile() {
        File csvFile = null;
        BufferedWriter csvWtriter = null;
        csvFile = new File(ImageUtils.mapPath + "testSleep.csv");
        File parent = csvFile.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        try {
            csvFile.createNewFile();
            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);

            String[] head = {"日期", "睡眠质量","备注"};
            List<String> headList = Arrays.asList(head);
            HashMap<Integer,String[]>dataHashMap=new HashMap<>();
            initSleepData(dataHashMap);
            int[]fiveSleepData=new int[576];
            for (int i = 0; i < fiveSleepData.length; i++) {
                fiveSleepData[i] = -1;//睡眠数据0为有效数据
            }
            List<SleepData> sleepDataList = SleepDataDaoManager.queryData("19.07.07", "19.07.09");
            for(SleepData sleepData:sleepDataList){
                String time=sleepData.getTime();
                String data=sleepData.getDateString();
                int startCount = DateUtil.get5MIndex(time, "19.07.07 12:00:00");
                String[]dataArray=dataHashMap.get(startCount);
                Log.i(TAG, "createSleepCsvFile: "+time+" "+startCount);
                dataArray[1]=data;
                fiveSleepData[startCount]= Integer.valueOf(data) == 0 ? (int) (1 + Math.random() * 7) : Integer.valueOf(data);
            }
            List<Integer> sleepTime = getSleepTime(fiveSleepData);
            for (int i = 0; i < sleepTime.size() / 2; i++) {
                int goBed=sleepTime.get(i * 2);
                int upBed=sleepTime.get(i * 2 + 1);
                String[]dataArray=dataHashMap.get(goBed);
                dataArray[2]="入睡";
                String[]dataArray2=dataHashMap.get(upBed);
                dataArray2[2]="起床";
            }
            writeRow(headList, csvWtriter);
            for (Map.Entry<Integer, String[]> entry : dataHashMap.entrySet()) {
                String[] values = entry.getValue();
                writeRowContent(values, csvWtriter);
            }
//            for (List<String> list : dataList) {
//                writeRow(list, csvWtriter);
//            }
           // List<String> contentList = Arrays.asList(dataArrays);
            //writeRowContent(contentList, csvWtriter);
            csvWtriter.flush();
            csvWtriter.close();
        } catch (
                IOException e) {
            e.printStackTrace();
        }

    }

    private static void writeRow(List<String> row, BufferedWriter csvWriter) throws IOException {
        for (Object data : row) {
            StringBuffer sb = new StringBuffer();
            String rowStr = sb.append("\"").append(data).append("\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }

    private static void writeRowContent(String[]values, BufferedWriter csvWriter) throws IOException {
        for (String data : values) {
            StringBuffer sb = new StringBuffer();
            String rowStr = sb.append("\"").append(data).append("\",").toString();
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();

    }

    private static void initData(HashMap<Integer,String[]>hashMap,String startDate) throws IOException {

        int length=6;
        for (int i = 0; i < 2880; i++) {
            String[]data=new String[length];
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < length; j++) {
                if (j == 0) {
                    data[j]=DateUtil.getCountTime(i, startDate);
               //     sb.append("\"").append().append("\",");
                } else {
                    data[j]="--";
                   // sb.append("\"").append("--").append("\",");
                }

            }
            hashMap.put(i,data);
        }

    }
    private static void initSleepData(HashMap<Integer,String[]>hashMap) throws IOException {
        String startDate = "19.07.07 12:00:00";
        for (int i = 0; i < 576; i++) {
            String[]data=new String[3];
            for (int j = 0; j < 3; j++) {
                if (j == 0) {
                    data[j]=DateUtil.getSleepCountTime(i, startDate);
                } else {
                    data[j]="--";
                }

            }
            hashMap.put(i,data);
        }

    }
    private static List<Integer> getSleepTime(int[] fiveSleepData) {
        List<Integer> list = new ArrayList<>();
        int goBed = -1;
        int upBed = 0;
        int offCount = 0;
        for (int i = 0; i < fiveSleepData.length; i++) {
            int data = fiveSleepData[i];
            if (data != -1) {
                offCount = 0;
                if (goBed == -1) {
                    list.add(i);
                    goBed = i;
                }

            } else {
                offCount++;
                if (offCount == 6 && goBed != -1) {//30分钟离床
                    list.add(i - 5);
                    offCount = 0;
                    goBed = -1;
                }
            }
            if(i==fiveSleepData.length-1&&goBed!=-1){
                list.add(i);
            }
        }
        return list;
    }

}
